package com.yirui.serialcomm.core.domain;

import org.bouncycastle.asn1.*;

import java.io.IOException;

/**
 * 串口传输包
 * @author Dujie
 * @create 2025/8/7
 * @since 1.0.0
 */
public class ASN1SerialCommPacket extends ASN1Object implements SerialCommPacket{
    private final StreamType type;
    private  byte[] data;
   // private final byte[] EMPTY_BYTES = new byte[0];

    public ASN1SerialCommPacket(StreamType type, byte[] data){
        this.type = type;
        this.data = data;  // 防御性拷贝
    }
    public static byte[] packWith(StreamType type, byte[] buffer) throws IOException {
        ASN1SerialCommPacket packet = new ASN1SerialCommPacket(type, buffer);
        //return ZipUtils.compress(packet.toASN1Primitive().getEncoded());
        return packet.toASN1Primitive().getEncoded();
    }

    public static byte[] packWithTCP(byte[] buffer) throws IOException {
       return packWith(StreamType.TCP, buffer);
    }

    public static byte[] packWithUDP(byte[] buffer) throws IOException {
        return packWith(StreamType.UDP, buffer);
    }

    public StreamType getType() {
        return type;
    }

    public byte[] getData() {
        return data;
    }

    @Override
    public int getSize() {
        return data == null ?0:data.length;
    }

    @Override
    public void setData(byte[] data) {
        this.data = data;
    }

    @Override
    public ASN1Primitive toASN1Primitive() {
        ASN1EncodableVector vector = new ASN1EncodableVector();
        vector.add(new ASN1Integer(type.ordinal()));

        vector.add(new DEROctetString(data));

        return new DERSequence(vector);
    }



    public static ASN1SerialCommPacket getInstance(Object obj){
        if (obj instanceof ASN1SerialCommPacket) {
            return (ASN1SerialCommPacket)obj;
        }
        if (obj != null) {
            ASN1Sequence seq = ASN1Sequence.getInstance(obj);
            int type = ASN1Integer.getInstance(seq.getObjectAt(0)).getValue().intValue();
            byte[] data = ASN1OctetString.getInstance(seq.getObjectAt(1)).getOctets();
            return new ASN1SerialCommPacket(type == 0?StreamType.TCP:StreamType.UDP, data);
        }
        return null;
    }
}
